package org.example.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.exception.BusinessException;
import org.example.mapper.ClazzMapper;
import org.example.mapper.StudentMapper;
import org.example.pojo.Clazz;
import org.example.pojo.ClazzQueryParam;
import org.example.pojo.PageResult;
import org.example.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    /*
    * 分页查询班级信息
    * */
    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        // 1.设置分页参数
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());

        // 2.执行查询
        List<Clazz> clazzList = clazzMapper.list(clazzQueryParam);
        // 处理状态
        LocalDate now = LocalDate.now();
        clazzList.forEach(clazz -> {
            LocalDate startDate = clazz.getBeginDate();
            LocalDate endDate = clazz.getEndDate();
            if (now.isAfter(endDate))
                clazz.setStatus("已结课");
            else if (!now.isBefore(startDate) && !now.isAfter(endDate))
                clazz.setStatus("在读中");
            else
                clazz.setStatus("未开班");
        });
        // 3.返回查询结果
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult<Clazz>(p.getTotal(), p.getResult());
    }

    /*
    * 新增班级
    * */
    @Override
    public void add(Clazz clazz) {
        // 1.设置默认状态
        clazz.setStatus("未开班");
        // 2.设置时间
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        clazzMapper.insert(clazz);
    }

    /*
    * 删除班级
    * */
    @Override
    public void deleteById(Integer id) {
        // 1.判断班级下是否有同学
        int studentCount = studentMapper.countByClazzId(id);
        if (studentCount > 0) {
            throw new BusinessException("删除失败：该班级下仍有 " + studentCount + " 名学生");
        }
        clazzMapper.deleteById(id);
    }

    /*
    * 根据ID查询班级信息
    * */
    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void update(Clazz clazz) {
        // 1.设置更新时间
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public List<Clazz> All() {
        return clazzMapper.All();
    }
}
